package dba.example.guice.dao.impl

import com.google.inject.persist.Transactional

import dba.example.entities.Company
import dba.example.guice.dao.CompanyDao
import dba.example.guice.finders.CompanyFinder
import javax.inject.Inject
import javax.persistence.EntityManager

class CompanyDaoImpl @Inject() (val em: EntityManager, val cf: CompanyFinder) extends CompanyDao {

  override def findAll() = cf.findAll()

  override def get(id: Integer): Company = em.find(classOf[Company], id)

  override def get(name: String): Company = {
    val companies = cf.getByNameSort(name.toLowerCase)
    if (companies.isEmpty()) {
      null
    } else {
      companies.get(0)
    }
  }

  @Transactional(rollbackOn = Array(classOf[Exception]))
  override def save(company: Company): Company = {
    
    if (company.name == null || company.name.isEmpty()) {
      throw new Exception("Name is manditory")
    }
    if (company.name.length > 100) {
      throw new Exception("Name is too long")
    }
    
    if (company.id == null) {
      if (get(company.name) != null) {
        throw new Exception("Name is already used")
      }
      
      em.merge(company)
    } else {
      val persisted = get(company.id)
      if (persisted == null) {
        throw new Exception("Invalid id")
      }
      if (!persisted.name.equalsIgnoreCase(company.name)) {
        if (get(company.name) != null) {
          throw new Exception("Name is already used")
        }
      }
      
      persisted.name = company.name
      em.merge(persisted)
    }
  }
  
  @Transactional
  override def remove(company: Company): Unit = em.remove(company)

}